<script setup>
	import { ref, onMounted } from 'vue'
	import { useUserStore } from '@/store/userInfo'

	const userStore = useUserStore( )
	const orderApi = uniCloud.importObject( 'order' )

	// 防抖函数
	const showToastDebounced = ( ( ) => {
		let timer = null
		return ( options ) => {
			if ( timer ) clearTimeout( timer )
			timer = setTimeout( ( ) => {
				uni.showToast( options )
			}, 300 )
		}
	} )( )

	// 订单列表数据
	const orderList = ref( [ ] )
	// 弹窗引用
	const popup = ref( null )
	// 是否编辑模式
	const isEdit = ref( false )
	// 订单状态选项
	const orderStates = [
		{ text: '全部', value: 0 },
		{ text: '待付款', value: 1 },
		{ text: '待发货', value: 2 },
		{ text: '待收货', value: 3 },
		{ text: '已完成', value: 4 }
	]

	// 添加表单数据的响应式定义
	const formData = ref( {
		_id: '',
		order_no: '',
		state: 0,
		recipient: '',
		recipientMobile: '',
		address: '',
		tatalNum: 0,
		tatalPrice: 0,
		cart_list: [ ]
	} )

	// 当前选中的状态
	const activeState = ref(0)

	// 获取订单列表
	const getOrderList = async (state = activeState.value) => {
		try {
			const result = await orderApi.getAllOrders(userStore.userInfo.role[0], state)
			if (result.errCode === 0) {
				orderList.value = result.data
			} else {
				showToastDebounced({
					title: result.errMsg,
					icon: 'none'
				})
			}
		} catch (e) {
			showToastDebounced({
				title: '获取订单列表失败',
				icon: 'none'
			})
		}
	}

	// 切换订单状态
	const changeState = (state) => {
		activeState.value = state
		getOrderList(state)
	}

	// 打开编辑订单弹窗
	const handleEdit = ( item ) => {
		isEdit.value = true
		// 只复制需要的字段
		formData.value = {
			_id: item._id,
			order_no: item.order_no,
			state: item.state,
			recipient: item.recipient,
			recipientMobile: item.recipientMobile,
			address: item.address,
			tatalNum: item.tatalNum,
			tatalPrice: item.tatalPrice,
			cart_list: item.cart_list || [ ]
		}
		popup.value.open( )
	}

	// 提交表单
	const submitForm = async ( ) => {
		try {
			const result = await orderApi.updateOrderState(
				formData.value.order_no,
				formData.value.state
			)

			if ( result.errCode === 0 ) {
				popup.value.close( )
				setTimeout( ( ) => {
					showToastDebounced( {
						title: '更新成功',
						icon: 'success'
					} )
				}, 500 )
				getOrderList( )
			} else {
				setTimeout( ( ) => {
					showToastDebounced( {
						title: result.errMsg,
						icon: 'none'
					} )
				}, 500 )
			}
		} catch ( e ) {
			showToastDebounced( {
				title: '更新失败',
				icon: 'none'
			} )
		}
	}

	// 添加删除订单方法
	const handleDelete = async ( order_no ) => {
		try {
			const res = await uni.showModal( {
				title: '提示',
				content: '确定要删除该订单吗？',
				confirmColor: '#ff4d4f'
			} )

			if ( !res.confirm ) return

			const result = await orderApi.deleteOrder( order_no )
			if ( result.errCode === 0 ) {
				showToastDebounced( {
					title: '删除成功',
					icon: 'success'
				} )
				getOrderList( )
			} else {
				showToastDebounced( {
					title: result.errMsg,
					icon: 'none'
				} )
			}
		} catch ( e ) {
			showToastDebounced( {
				title: '删除失败',
				icon: 'none'
			} )
		}
	}

	onMounted( ( ) => {
		getOrderList( )
	} )
</script>

<template>
	<view class="order-list">
		<!-- 状态切换栏 -->
		<view class="state-switch">
			<view 
				v-for="state in orderStates" 
				:key="state.value"
				class="state-item"
				:class="{ active: activeState === state.value }"
				@tap="changeState(state.value)"
			>
				{{ state.text }}
			</view>
		</view>

		<!-- 订单列表 -->
		<view class="list">
			<view v-if="orderList.length === 0" class="empty-tip">
				暂无相关订单
			</view>
			<view class="item" v-for="item in orderList" :key="item._id">
				<view class="order-info">
					<view class="header">
						<text class="order-no">订单号：{{ item.order_no }}</text>
						<text
							class="state"
							:class="{
								'wait-pay': item.state === 1,
								'wait-send': item.state === 2,
								'wait-receive': item.state === 3,
								'completed': item.state === 4
							}"
						>{{ orderStates.find(state => state.value === item.state)?.text }}</text>
					</view>
					<view class="goods-list">
						<view class="goods-item" v-for="(goods, index) in item.cart_list" :key="index">
							<image class="goods-img" :src="goods.cover_pic" mode="aspectFill" />
							<view class="goods-info">
								<view class="goods-name">{{ goods.name }}</view>
								<view class="goods-price">
									<text class="price">¥{{ Number(goods.buy_price).toFixed(2) }}</text>
									<text class="num">x{{ goods.num }}</text>
								</view>
							</view>
						</view>
					</view>
					<view class="content">
						<view class="user-info">
							<text class="label">收货人：</text>
							<text class="value">{{ item.recipient }}</text>
							<text class="mobile">{{ item.recipientMobile }}</text>
						</view>
						<view class="address">
							<text class="label">地址：</text>
							<text class="value">{{ item.address }}</text>
						</view>
						<view class="cart-info">
							<text class="label">商品数量：</text>
							<text class="value">{{ item.cart_list.reduce((total, goods) => total + goods.num, 0) }}件</text>
							<text class="price">合计：¥{{ Number(item.tatalPrice).toFixed(2) }}</text>
						</view>
					</view>
					<view class="actions" style="margin-left: auto; width: fit-content;">
						<button class="btn edit" @tap="handleEdit(item)">修改状态</button>
						<button class="btn delete" @tap="handleDelete(item.order_no)">删除</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部安全区域占位 -->
		<view class="safe-area"></view>

		<!-- 编辑弹窗 -->
		<uni-popup ref="popup" type="dialog">
			<view class="popup-content">
				<view class="popup-title">修改订单状态</view>
				<view class="form-item">
					<text class="label">订单状态</text>
					<picker :range="orderStates" range-key="text"
						:value="orderStates.findIndex(state => state.value === formData.state)"
						@change="e => formData.state = orderStates[e.detail.value].value">
						<view class="picker">
							{{ orderStates.find(state => state.value === formData.state)?.text || '请选择状态' }}
						</view>
					</picker>
				</view>
				<view class="popup-buttons">
					<button class="btn cancel" @tap="popup.close()">取消</button>
					<button class="btn confirm" @tap="submitForm">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<style lang="scss" scoped>
	.order-list {
		min-height: 100vh;
		padding: 24rpx;
		padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
		background-color: $page-bg-color;

		.list {
			.item {
				margin-bottom: 24rpx;
				padding: 24rpx;
				background-color: #fff;
				border-radius: 16rpx;

				.order-info {
					.header {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 24rpx;
						padding-bottom: 24rpx;
						border-bottom: 2rpx solid $line-color-aux;

						.order-no {
							font-size: 24rpx;
							color: $text-font-color-2;
						}

						.state {
							font-size: 24rpx;
							// 订单状态颜色
							&.wait-pay {
								color: #ff4d4f;  // 待付款-红色
							}
							
							&.wait-send {
								color: #faad14;  // 待发货-橙色
							}
							
							&.wait-receive {
								color: #1890ff;  // 待收货-蓝色
							}
							
							&.completed {
								color: #52c41a;  // 已完成-绿色
							}
						}
					}

					.content {

						.user-info,
						.address,
						.cart-info {
							display: flex;
							align-items: center;
							margin-bottom: 16rpx;
							font-size: 24rpx;

							.label {
								color: $text-font-color-2;
							}

							.value {
								color: $text-font-color-1;
							}

							.mobile {
								margin-left: 24rpx;
								color: $text-font-color-1;
							}

							.price {
								margin-left: auto;
								color: #ff4d4f;
								font-weight: 600;
							}
						}
					}

					.actions {
						display: flex;
						align-items: center;
						gap: 24rpx;

						.btn {
							padding: 8rpx 24rpx;
							border-radius: 8rpx;
							font-size: 22rpx;
							line-height: 1.5;
							background-color: transparent;

							&::after {
								border: none;
							}

							&.edit {
								color: $brand-theme-color;
								border: 2rpx solid $brand-theme-color;
							}

							&:active {
								opacity: 0.8;
							}

							&.delete {
								color: #ff4d4f;
								border: 2rpx solid #ff4d4f;
							}

							&:not(:last-child) {
								margin-right: 24rpx;
							}
						}
					}
				}
			}
		}

		.safe-area {
			height: 120rpx;
			width: 100%;
		}
	}

	.popup-content {
		padding: 24rpx;
		width: 560rpx;
		background-color: #fff;
		border-radius: 12rpx;

		.popup-title {
			text-align: center;
			font-size: 28rpx;
			font-weight: 600;
			margin-bottom: 24rpx;
		}

		.form-item {
			margin-bottom: 24rpx;

			.label {
				display: block;
				margin-bottom: 12rpx;
				font-size: 24rpx;
				color: $text-font-color-2;
			}

			.picker {
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				padding: 0 24rpx;
				background-color: $page-bg-color;
				border-radius: 8rpx;
				font-size: 24rpx;
				box-sizing: border-box;
			}
		}

		.popup-buttons {
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 24rpx;
			gap: 24rpx;

			.btn {
				flex: 1;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 0;
				border-radius: 8rpx;
				font-size: 24rpx;

				&.cancel {
					background-color: $page-bg-color;
					color: $text-font-color-2;
				}

				&.confirm {
					background-color: $brand-theme-color;
					color: #fff;
				}

				&:active {
					opacity: 0.8;
				}
			}
		}
	}

	.goods-list {
		margin: 24rpx 0;
		
		.goods-item {
			display: flex;
			align-items: center;
			padding: 16rpx 0;
			
			.goods-img {
				width: 120rpx;
				height: 120rpx;
				border-radius: 8rpx;
				margin-right: 16rpx;
			}
			
			.goods-info {
				flex: 1;
				
				.goods-name {
					font-size: 24rpx;
					color: $text-font-color-1;
					margin-bottom: 8rpx;
				}
				
				.goods-price {
					display: flex;
					justify-content: space-between;
					align-items: center;
					
					.price {
						font-size: 24rpx;
						color: #ff4d4f;
					}
					
					.num {
						font-size: 22rpx;
						color: $text-font-color-2;
					}
				}
			}
		}
	}

	/* 状态切换栏样式 */
	.state-switch {
		display: flex;
		justify-content: space-between;
		padding: 0 32rpx;
		background-color: #fff;
		border-bottom: 1px solid $line-color-aux;
		margin-bottom: 24rpx;

		.state-item {
			position: relative;
			padding: 24rpx 0;
			font-size: 28rpx;
			color: #666;

			&.active {
				color: $brand-theme-color;
				font-weight: bold;

				&::after {
					content: '';
					position: absolute;
					left: 50%;
					bottom: 16rpx;
					transform: translateX(-50%);
					width: 40rpx;
					height: 4rpx;
					background-color: $brand-theme-color;
					border-radius: 2rpx;
				}
			}
		}
	}

	/* 空状态提示样式 */
	.empty-tip {
		padding: 40rpx;
		text-align: center;
		color: $text-font-color-3;
		font-size: 28rpx;
	}
</style>